package woncode.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UploadController {
	byte[] bytes=new byte[1024];
	String fileName;
	boolean isFinish;
	
	@RequestMapping(value="/UploadFile",method=RequestMethod.POST)
	public synchronized void postFile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception{
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload fileUpload=new ServletFileUpload(factory);
		fileUpload.setFileSizeMax(10000*1024*1024);
		fileUpload.setSizeMax(10000*1024*1024);

		ArrayList<Object> fileContextList = null;
		int fileID=0;
		List<FileItem> fileList = fileUpload.parseRequest(req);
		for(FileItem fileItem:fileList){
			if(fileItem.isFormField()){
				fileID=Integer.parseInt(fileItem.getString());
				System.out.println("UploadFileId: "+fileID);
				fileContextList=UtilContext.fileContextMap.get(fileID);
			}else {
				this.fileName=fileItem.getName();
				fileContextList.add(this);
				DownloadController downloadController=(DownloadController)fileContextList.get(1);
				InputStream uploadInputStream=fileItem.getInputStream();
				while(uploadInputStream.read(this.bytes)!=-1){
					downloadController.selfNotifyAll();
					this.wait();
				}
				System.out.println("finish upload");
				this.isFinish=true;
				downloadController.selfNotifyAll();
			}
		}
		System.out.println("upload ok");
	}
	
	public synchronized void selfNotifyAll(){
		this.notify();
	}
}
